package com.zoke.password.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zoke.password.Conf;
import com.zoke.password.R;
import com.zoke.password.base.BaseActivity;
import com.zoke.password.dialog.AppLoading;
import com.zoke.password.model.Password;
import com.zoke.password.model.Result;
import com.zoke.password.tools.PwdCheckUtil;
import com.zoke.password.tools.StringUtils;
import com.zoke.password.tools.UToast;

import org.xutils.common.util.LogUtil;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import io.nebulas.Constants;
import io.nebulas.api.SmartContracts;
import io.nebulas.model.GoodsModel;
import io.nebulas.utils.Util;

@ContentView(R.layout.activity_add)
public class AddActivity extends BaseActivity {

    @ViewInject(R.id.tv_title)
    TextView tv_title;
    @ViewInject(R.id.iv_back)
    ImageView iv_back;
    @ViewInject(R.id.et_title)
    EditText et_title;
    @ViewInject(R.id.et_account)
    EditText et_account;
    @ViewInject(R.id.et_password)
    EditText et_password;
    @ViewInject(R.id.iv_level)
    ImageView iv_level;
    @ViewInject(R.id.tv_level)
    TextView tv_level;
    @ViewInject(R.id.et_tip)
    EditText et_tip;

    //执行网络请求
    private AppLoading loading;
    private String serialNumber = "";
    private boolean isDo = false;

    public static final int ADD = 20000;

    private Password mPasswordModel;


    /**
     * @param activity
     */
    public static void open(Activity activity) {
        activity.startActivityForResult(new Intent(activity, AddActivity.class), ADD);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tv_title.setText(R.string.add);
        iv_back.setVisibility(View.VISIBLE);
        et_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());//显示
        loading = new AppLoading(this, false, R.string.loading);
        et_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = s.toString();
                if (TextUtils.isEmpty(text)) {
                    iv_level.setVisibility(View.INVISIBLE);
                    tv_level.setVisibility(View.INVISIBLE);
                    return;
                }
                iv_level.setVisibility(View.VISIBLE);
                tv_level.setVisibility(View.VISIBLE);
                PwdCheckUtil.LEVEL sng = PwdCheckUtil.checkPassword(text);
                String tips = getString(R.string.password_strong);
                int levelColor;
                int levelDrw;
                switch (sng) {
                    case EASY:
                        tips = String.format(tips, getString(R.string.password_easy));
                        levelColor = R.color.level_1;
                        levelDrw = R.drawable.shape_level_1;
                        break;
                    case MIDIUM:
                        tips = String.format(tips, getString(R.string.password_mid));
                        levelColor = R.color.level_2;
                        levelDrw = R.drawable.shape_level_2;
                        break;
                    case STRONG:
                        tips = String.format(tips, getString(R.string.password_str));
                        levelColor = R.color.level_3;
                        levelDrw = R.drawable.shape_level_3;
                        break;
                    case EXTREMELY_STRONG:
                    case VERY_STRONG:
                    default:
                        tips = String.format(tips, getString(R.string.password_very));
                        levelColor = R.color.level_4;
                        levelDrw = R.drawable.shape_level_4;
                        break;
                }
                tv_level.setText(tips);
                tv_level.setTextColor(getResources().getColor(levelColor));
                iv_level.setBackgroundResource(levelDrw);
                LogUtil.e("sng=" + tips);
            }
        });
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        if (mImmersionBar != null)
            mImmersionBar.statusBarDarkFont(true)
                    .statusBarView(R.id.status)
                    .init();
    }

    @Event({R.id.iv_back, R.id.btn_create, R.id.btn_save})
    private void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                onBackPressed();
                break;
            case R.id.btn_create:
                String getStringRandom = StringUtils.generatePassword();
                et_password.setText(getStringRandom);
                break;
            case R.id.btn_save:
                save();
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isDo) {
            nasQueryTransferStatus();
        }
    }

    /**
     * 执行保存
     */
    private void save() {
        String[] args = checkParams();
        if (args == null) return;
        isDo = true;
        if (loading != null) loading.show();
        //一次请求对应一个码
        serialNumber = Util.getRandomCode(Constants.RANDOM_LENGTH);
        GoodsModel goods = new GoodsModel();
        goods.name = "保存";
        goods.desc = "-执行云备份信息";
        String functionName = "addPassword";
        //password, preference
        SmartContracts.call(this, Constants.MAIN_NET, goods, functionName, Conf.SMART, Conf.VALUE, args, serialNumber);

    }

    private String[] checkParams() {
        String[] args = null;
        String title = et_title.getText().toString().trim();
        if (TextUtils.isEmpty(title)) {
            UToast.show(this, R.string.empty_title);
            return args;
        }
        String account = et_account.getText().toString().trim();
        if (TextUtils.isEmpty(account)) {
            UToast.show(this, R.string.empty_account);
            return args;
        }
        String password = et_password.getText().toString().trim();
        if (TextUtils.isEmpty(password)) {
            UToast.show(this, R.string.empty_password);
            return args;
        }
        String tips = et_tip.getText().toString().trim();
        if (TextUtils.isEmpty(tips))
            tips = "";
        //title, account, password, tips
        mPasswordModel = new Password();
        mPasswordModel.title = title;
        mPasswordModel.account = account;
        mPasswordModel.password = password;
        mPasswordModel.tips = tips;
        args = new String[]{title, account, password, tips};
        return args;
    }


    public void nasQueryTransferStatus() {
        isDo = false;
        if (TextUtils.isEmpty(serialNumber)) {
            if (loading != null) loading.dismiss();
            return;
        }
        SmartContracts.queryTransferStatus(Constants.MAIN_NET, serialNumber, new SmartContracts.StatusCallback() {
            @Override
            public void onSuccess(final String response) {
                LogUtil.e("onSuccess :" + response);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (loading != null) loading.dismiss();
                        if (TextUtils.isEmpty(response)) {
                            UToast.show(AddActivity.this, R.string.save_error);
                            return;
                        }
                        Result result = new Gson().fromJson(response, Result.class);
                        if (result == null) {
                            UToast.show(AddActivity.this, R.string.save_error);
                            return;
                        }
                        if (result.code != 0) {
                            UToast.show(AddActivity.this, AddActivity.this.getString(R.string.save_error) + ":" + result.msg);
                            return;
                        }
                        UToast.show(AddActivity.this, R.string.save_success);
                        if (mPasswordModel != null) {
                            Intent intent = new Intent();
                            intent.putExtra("json", new Gson().toJson(mPasswordModel));
                            setResult(ADD, intent);
                        }
                        finish();
                    }
                });
            }

            @Override
            public void onFail(final String error) {
                LogUtil.e("onFail " + error);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (loading != null) loading.dismiss();
                        UToast.show(AddActivity.this, AddActivity.this.getString(R.string.save_error) + ":" + error.toString());
                    }
                });
            }
        });
    }

}
